%%房间中心
-module(fun_room_center).
-include("common.hrl").

-export([req_create_room/4,req_create_room/5,req_reenter_room/3,req_join_room/4]).
-export([created_room/1,room_start_game/1,destroyed_room/1,get_hid/1,send_to_room/2,create_room/4,req_join_sg_room/4]).
%%请求创建房间 GroupId=0普通创建房间,GroupId !=0群创建房间
req_create_room(Sid,Aid,Req,Seq)->
	req_create_room(Sid,Aid,Req,Seq,0).
req_create_room(Sid,Aid,Req,Seq,GroupId) ->
	Need = fun_player:need_card(Req),
	case fun_player:check_card(Aid, Need) of
		true ->
%% 			fun_player:spend_card(Sid,Aid, Need),
			create_room(Sid,Aid,Req,Seq,GroupId);
		_ -> skip
	end,
	ok.


%%请求重进入房间
req_reenter_room(Sid,Aid,RoomID) ->
	?debug("req_reenter_room,{Sid,Aid,RoomID} = ~p",[{Sid,Aid,RoomID}]),
	case db:dirty_get(room, RoomID) of
		[#room{hid=Hid} | _] when erlang:is_pid(Hid) ->
			?debug("req_reenter_room,{Hid} = ~p",[{Hid}]),
  			gen_server:cast(Hid, {req_reenter_room,{Sid,fun_player:get_acc(Aid)}});
		_ -> skip
	end,
	ok.
%%请求进入房间
req_join_room(Sid,Aid,IDStr,Seq) ->
	case db:dirty_get(room, util:to_integer(IDStr)) of
		[#room{hid=Hid,room_status= ?ROOM_WAIT} | _] when erlang:is_pid(Hid) ->
			gen_server:cast(Hid, {req_join_room,{Sid,fun_player:get_acc(Aid),Seq}});
		_ -> skip
	end,	
	ok.

req_join_sg_room(Sid,Aid,IDStr,Seq) ->
	case db:dirty_get(room, util:to_integer(IDStr)) of
		[#room{hid=Hid} |_] when erlang:is_pid(Hid) ->
			gen_server:cast(Hid, {req_join_room,{Sid,fun_player:get_acc(Aid),Seq}});
		_ -> skip
	end,	
	ok.

%%创建房间  sort=0普通创建房间,sort!=0 群创建房间
create_room(Sid,Aid,Req,Seq)->
	create_room(Sid,Aid,Req,Seq,0).
create_room(Sid,Aid,Req,Seq,GroupId) ->
	RoomID = 800000 + db:get_sql_new_id(sys_room),
	db:dirty_put(#room{id = RoomID,owner=Aid,hid=0,create_time=0,group_id=GroupId,req=Req}),
	gen_server:cast({global, room_ctr}, {req_create_room,{Sid,fun_player:get_acc(Aid),Req,RoomID,"",Seq}}).


created_room({ID,Hid}) ->
	case db:dirty_get(room, ID) of
		[Room | _] ->
			db:dirty_put(Room#room{hid = Hid,create_time=util:unixtime(),room_status = ?ROOM_WAIT});
		_ -> skip
	end.
%%房间开始游戏
room_start_game(ID) ->
	case db:dirty_get(room, ID) of
		[Room | _] ->
			db:dirty_put(Room#room{room_status = ?ROOM_GAME});
		_ -> skip
	end.
%%解散房间
destroyed_room(ID) ->
	db:dirty_del(room, ID).

%%获取房间id
get_hid(RoomID) ->
	case db:dirty_get(room, RoomID) of
		[Room | _] -> Room#room.hid;
		_ -> 0
	end.
%%向房间发送消息
send_to_room(RoomID,Msg) ->
	case get_hid(RoomID) of
		Hid when erlang:is_pid(Hid) -> gen_server:cast(Hid, Msg);
		_ -> skip
	end.